package com.kaaction.common.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.util.UriUtils;

import com.kaaction.common.config.Global;
import com.kaaction.modules.market.entity.Works;
import com.kaaction.modules.market.service.WorksService;
import com.kaaction.modules.operate.entity.Client;
import com.kaaction.modules.operate.service.ClientService;

public class UserfilesUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private boolean isMultipart;
	   private int maxFileSize = 5 * 1024 * 1024;
	   private int maxMemSize = 4 * 1024;
	   private File file ;
	   
	   @Autowired
		private WorksService worksService;
		
		@Autowired
		private ClientService clientService;

	 public void init( ){
	      // Get the file location where it would be stored.
	 }
	 
	public void fileOutputStream(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
//		String  userName = request.getParameter("username");
//		String  mobile = request.getParameter("usertel");
//		String  remarks = request.getParameter("kind");
//		
//		Client client = new Client();
//        client.setName(userName);
//        client.setMobile(mobile);
//        clientService.save(client);
//        
		// Check that we have a file upload request
	      isMultipart = ServletFileUpload.isMultipartContent(request);
	      response.setContentType("text/html");
	      java.io.PrintWriter out = response.getWriter( );
	   
	      if( !isMultipart ) {
	         out.println("<html>");
	         out.println("<head>");
	         out.println("<title>Servlet upload</title>");  
	         out.println("</head>");
	         out.println("<body>");
	         out.println("<p>No file uploaded</p>"); 
	         out.println("</body>");
	         out.println("</html>");
	         return;
	      }
	  
	      DiskFileItemFactory factory = new DiskFileItemFactory();
	   
	      // maximum size that will be stored in memory
	      factory.setSizeThreshold(maxMemSize);
	      
	      String diskLoc = request.getRealPath("")  + "dynamic" + File.separator;
	   
	      // Location to save data that is larger than maxMemSize.
	      factory.setRepository(new File(diskLoc));

	      // Create a new file upload handler
	      ServletFileUpload upload = new ServletFileUpload(factory);
	   
	      // maximum file size to be uploaded.
	      upload.setSizeMax( maxFileSize );

	      try { 
	         // Parse the request to get file items.
	         List fileItems = upload.parseRequest(request);
		
	         // Process the uploaded file items
	         Iterator i = fileItems.iterator();

	         while ( i.hasNext () ) {
	            FileItem fi = (FileItem)i.next();
	            if ( !fi.isFormField () ) {
	               // Get the uploaded file parameters
	               String fieldName = fi.getFieldName();
	               String oldName = fi.getName();
	               int loc = oldName.lastIndexOf(".");
	               String fileName = String.valueOf(new Date().getTime()) + oldName.substring(loc);
	               String contentType = fi.getContentType();
	               boolean isInMemory = fi.isInMemory();
	               long sizeInBytes = fi.getSize();
	            
	               file = new File( diskLoc + fileName) ;
	               
//	               // Write the file
//	               if( fileName.lastIndexOf("\\") >= 0 ) {
//	                  file = new File( diskLoc + fileName.substring( fileName.lastIndexOf("\\"))) ;
//	               } else {
//	                  file = new File( diskLoc + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
//	               }
	               fi.write( file ) ;
	               
//	               Works work = new Works();
//	  	           work.setClient(client);
//	  	           work.setWorks(fileName);
//	  	           work.setOwnBy("1");
//	  	           work.setTitle("");
//	  	           work.setContent("");
//	  	           work.setRemarks(remarks);
//	  	           worksService.save(work);
//	  	           
	  	           
	               out.write(fileName);
	               out.flush();
	               out.close();
	            }
	         }
	         } catch(Exception ex) {
	        	 ex.printStackTrace();
	         }
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fileOutputStream(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fileOutputStream(req, resp);
	}
}
